<?php
/**
 * @author: xuzhengyang
 * @Time: 2023/2/8   17:11
 */


namespace app;

use think\Event;

class BaseEvent extends Event
{
    /**
     * 延迟执行时间
     * @var int
     */
    protected int $delay = -1;

    /**
     * 重试次数
     * @var int
     */
    protected int $retryMax = 0;

    /**
     * 设置超时时间
     * @param int $delay
     * @return $this
     */
    public function setDelay(int $delay = -1)
    {
        $this->delay = $delay;
        return $this;
    }

    /**
     * 设置重试次数
     * @param  int  $max
     * @return $this
     */
    public function setRetryMax(int $max = 0)
    {
        $this->retryMax = $max;
        return $this;
    }

    /**
     * 执行事件调度
     * @access protected
     * @param mixed $event  事件方法
     * @param mixed $params 参数
     * @return mixed
     */
    protected function dispatch($event, $params = null)
    {
        if (!is_string($event)) {
            $call = $event;
        } elseif (strpos($event, '::')) {
            $call = $event;
        } else {
            $obj  = $this->app->make($event);
            $call = [$obj, 'handle'];
        }

        if (is_array($call) && method_exists($call[0], 'isAsyncQueue') && $call[0]->isAsyncQueue()) {
            $data = [
                'params' => $params,
                'event' => $event,
                'retryMax' => $this->retryMax,
            ];
            $delays = $this->delay == -1 ? intval($call[0]->getDelay() ?? 0) : $this->delay;
            return $call[0]->dispatch($data, $delays);
        }

        return $this->app->invoke($call, [$params]);
    }
}